package com.baobao.common.spring;

import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class CallbackMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {

	// 做jsonp的支持的标识，在请求参数中加该参数
	private String callbackName;


	@Override
	protected void writePrefix(JsonGenerator generator, Object object) throws IOException {
		String jsonpFunction = getJsonpFunction();
		// 判断是否有callback
		if(StringUtils.isNotEmpty(jsonpFunction)){
			generator.writeRaw(jsonpFunction + "(");
		}
	}
	@Override
	protected void writeSuffix(JsonGenerator generator, Object object) throws IOException {
		String jsonpFunction = getJsonpFunction();
		// 判断是否有callback
		if(StringUtils.isNotEmpty(jsonpFunction)){
			generator.writeRaw(");");
		}
	}
	private String getJsonpFunction() {
		// 从threadLocal中获取当前的Request对象
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
				.getRequest();
		String jsonpFunction = request.getParameter(callbackName);
		return jsonpFunction;
	}

	public String getCallbackName() {
		return callbackName;
	}

	public void setCallbackName(String callbackName) {
		this.callbackName = callbackName;
	}

}
